/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package rallyracer;


import au.com.bytecode.opencsv.CSVReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.joda.time.DateTime;

/**
 *
 * @author samra_000
 */
public class SegmentParser 
{
    private static final int serialNumberLocation = 0;
    private static final int recommendedSpeedLocation = 1;
    private static final int distanceFromStartLocation = 2;
    private static final int pauseLocation = 3;
    
    public SegmentParser() throws FileNotFoundException
    {
         
         
    }
    
    public static Segment parse(File file) throws IOException, DuplicateDataPointInSegmentException
    {
        CSVReader parser = new CSVReader(new FileReader(file));
        //FirstLine will give you segment number
        String[] nextLine = parser.readNext();
        int segmentNumber = Integer.parseInt(nextLine[0]);
        nextLine = parser.readNext();
        DateTime startTime = DataPoint.dateFormatter.parseDateTime(nextLine[0]);
        System.out.println("SegmentNumber: " + segmentNumber );
        Segment s = new Segment(segmentNumber);
        s.setAbsoluteStartTime(startTime);
        
        while( ( nextLine = parser.readNext() ) != null )
        {
            String curText = nextLine[serialNumberLocation];
            int serialNumber = Integer.parseInt( curText );
            
            DataPoint p = new DataPoint( serialNumber );
            p.recommendedSpeed = parseFloatIfNotEmpty(nextLine[recommendedSpeedLocation] );
            p.distanceFromStart = parseFloatIfNotEmpty(nextLine[distanceFromStartLocation] );
            if( nextLine.length > pauseLocation )
            {
                p.pause = parseIntIfNotEmpty( nextLine[pauseLocation] );
            }
            s.add(p);
        }
        return s;
    }
    
    private static float parseFloatIfNotEmpty( String text )
    {
        if( text!=null && !text.trim().isEmpty() )
        {
            float recommendedSpeed = Float.parseFloat( text );
            return recommendedSpeed;
        }
        return -1;
    }
    
    private static int parseIntIfNotEmpty( String text )
    {
        if( text!=null && !text.trim().isEmpty() )
        {
            int recommendedSpeed = Integer.parseInt( text );
            return recommendedSpeed;
        }
        return -1;
    }
    
}
